<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-alert title="商品添加信息" type="info" show-icon center :closable="false" />

      <!-- 步骤条 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form :model="addForm" ref="addFormRef" :rules="addFormRules" label-width="100px" label-position='top'>
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave='beforeTableLeave' @tab-click='tableClisked'>
          <el-tab-pane label="基本信息" name='0'>
            <el-form-item label="商品名称" prop='goods_name'>
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop='goods_price'>
              <el-input v-model="addForm.goods_price" type='number'></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop='goods_weight'>
              <el-input v-model="addForm.goods_weight" type='number'></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop='goods_number'>
              <el-input v-model="addForm.goods_number" type='number'></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop='goods_cat'>
              <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="cateProps" @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name='1'>
            <el-form-item v-for='i in manyTableData' :key='i.attr_id' :label='i.attr_name'>
              <el-checkbox-group v-model="i.attr_vals">
                <el-checkbox v-for="(item,i2) in i.attr_vals1" :key="i2" :label="item" border>
                </el-checkbox>

              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name='2'>
            <el-form-item :label='i.attr_name' v-for="i in onlyTableData" :key='i.attr_id'>
              <el-input v-model="i.attr_vals" clearable></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name='3'>
            <el-upload class="upload-demo" :action="upLoadURL" :on-preview="handlePreview" :on-remove="handleRemove"
              :on-success='handleSuccess' :headers='headerObj' list-type="picture-card">
              <i class="el-icon-plus"></i>
              <!-- <el-button size="small" type="primary">点击上传</el-button> -->
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name='4'>
            <quill-editor v-model='addForm.goods_introduce'></quill-editor>
            <el-button type='primary' class="btnAdd" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <el-dialog title='图片浏览' :visible.sync='previewVisible' width='30%'>
        <el-image :src="previewPath" class="previewImg" />
      </el-dialog>
    </el-card>
  </div>
</template>

<script scoped>
import _ from 'lodash'
import { cateListAPI, paramsListAPI } from '@/api/categories'
import { ListGoodsAPI } from '@/api/list'
export default {
  // 组件名称
  name: 'demo',
  // 组件参数 接收来自父组件的数据
  props: {},
  // 局部注册的组件
  components: {},
  // 组件状态值
  data () {
    return {
      previewPath: '',
      previewVisible: false,
      upLoadURL: 'http://42.192.71.221:8889/api/private/v1/upload',
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      onlyTableData: [],
      manyTableData: [],
      selectekeys: [],
      cateProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      cateList: [],
      addForm: {
        goods_cat: [],
        goods_name: '',
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      addFormRules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
      },
      activeIndex: '0'
    }
  },
  // 计算属性
  computed: {},
  // 侦听器
  watch: {},
  // 组件方法
  methods: {
    handleSuccess (val) {
      const picInfo = { pic: val.data.tmp_path }
      this.addForm.pics.push(picInfo)
    },
    handleRemove (file) {
      console.log(file)
      const filePath = file.response.data.tmp_path
      const i = this.addForm.pics.findIndex(x => x.pic === filePath)
      this.addForm.pics.splice(i, 1)
    },
    handlePreview (file) {
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    cataeId () {
      if (this.selectekeys.length === 3) {
        return this.selectekeys[2]
      }
      return null
    },
    async tableClisked () {
      if (this.activeIndex === '1') {
        const { data: res } = await paramsListAPI(this.cataeId(), { sel: 'many' })
        this.manyTableData = res.data
        this.manyTableData.attr_vals1 = res.data.attr_vals
        res.data.forEach(i => {
          i.attr_vals1 = i.attr_vals = i.attr_vals.length === 0 ? [] : i.attr_vals.split(',')
        })
      } else if (this.activeIndex === '2') {
        const { data: res } = await paramsListAPI(this.cataeId(), { sel: 'only' })
        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    beforeTableLeave () {
      if (this.activeIndex === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    handleChange (val) {
      if (val.length !== 3) {
        this.addForm.goods_cat = []
      }
      this.selectekeys = val
    },
    async getCateList () {
      const { data: res } = await cateListAPI()
      this.cateList = res.data
    },
    add () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写必要的表单项！')
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        this.manyTableData.forEach(i => {
          const attrObj = {
            attr_id: i.attr_id,
            attr_value: i.attr_vals.join(',')
          }
          form.attrs.push(attrObj)
        })
        this.onlyTableData.forEach(i => {
          const attrObj = {
            attr_id: i.attr_id,
            attr_value: i.attr_vals
          }
          form.attrs.push(attrObj)
        })
        form.attrs = this.addForm.attrs
        const { data: res } = await ListGoodsAPI(form)
        if (res.meta.status !== 201) return this.$message.error('添加商品失败')
        this.$router.back()
      })
    }
  },
  /**
  * 组件实例创建完成，属性已绑定，但DOM还未生成，$ el属性还不存在
  */
  created () {
    this.getCateList()
  },
  /**
  * el 被新创建的 vm.$ el 替换，并挂载到实例上去之后调用该钩子。
  * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.$ el 也在文档内。
  */
  mounted () {
  }
}
</script>

<style>
.btnAdd {
  margin-top: 15px;
}
.previewImg {
  width: 100%;
}
.el-form-item__label {
  float: none;
}
.el-form-item__content {
  margin-top: 20px;
}
.el-steps {
  margin: 15px 0;
}
.el-step_title {
  font-size: 13px;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
  margin: 0;
}
</style>
